This tutorials shows how to use Canvas to draw a Line.
Syntax
import androidx.compose.foundation.Canvas
Canvas(Modifier.fillMaxSize()) {
drawLine(
color = Color.Red,
start = Offset(x = 400f, y = 200f),
end = Offset(x = 900f, y = 800f),
strokeWidth = 5f
)
}
In this example we use Canvas to draw Rectangle.
MainActivity.kt
package com.example.testcompose
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.setContent
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Canvas(Modifier.fillMaxSize()) {
drawLine(
color = Color.Red,
start = Offset(x = 400f, y = 200f),
end = Offset(x = 900f, y = 800f),
strokeWidth = 5f
)
}
}
}
}
Output